package com.hippy.erya.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hippy.erya.common.DateUtil;
import com.hippy.erya.entity.CostingDO;
import com.hippy.erya.entity.OrderDetailDO;
import com.hippy.erya.mapper.CostingMapper;
import com.hippy.erya.query.BaseQueryWrapper;
import com.hippy.erya.sys.core.constant.cache.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CostingServiceImpl extends ServiceImpl<CostingMapper, CostingDO> {

    @Autowired
    private CostingMapper costingMapper;

    public Page<CostingDO> queryByPage(long currentPage, int limit, String dataRange) {
        Page<CostingDO> page = new Page<>(currentPage, limit);
        QueryWrapper<CostingDO> queryWrapper = BaseQueryWrapper.buildQuery();
        BaseQueryWrapper.buildQuery(queryWrapper, dataRange, "COSTING_DATE");
        Page<CostingDO> pageResult = costingMapper.selectPage(page, queryWrapper);
        pageResult.getRecords().forEach(BaseQueryWrapper::outputMessage);
        return pageResult;
    }

    public void insert(CostingDO costingDO) {
        costingMapper.insert(costingDO);
    }


    public CostingDO queryById(long id) {
        return costingMapper.selectById(id);
    }

    public List<CostingDO> queryLatestCosting() {
        QueryWrapper<CostingDO> queryWrapper = BaseQueryWrapper.buildQuery();
        queryWrapper.ge("COSTING_DATE", DateUtil.plusDays(DateUtil.getCurrentDate(), -7));
        return costingMapper.selectList(queryWrapper);
    }

    public CostingDO queryByOrderDate(Date orderDate, String userCode) {
        QueryWrapper<CostingDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("USABLE_FLAG", Cache.USABLE);
        queryWrapper.eq("USER_CODE", userCode);
        Date formatDate = DateUtil.formatToDate(orderDate, DateUtil.DATE_SHOW_FORMAT);
        queryWrapper.ge("COSTING_DATE", formatDate);
        queryWrapper.le("COSTING_DATE", DateUtil.plusDays(formatDate, 1));
        return costingMapper.selectOne(queryWrapper);
    }


}
